package com.zhigh.project.security.jwt.authentication.principal;

import com.zhigh.project.security.jwt.authentication.JWT;
import com.zhigh.project.security.jwt.authentication.JWTPayload;
import org.springframework.security.core.CredentialsContainer;

import java.security.Principal;
import java.util.Optional;

public abstract class AbstractJWTPrincipal implements Principal, CredentialsContainer {

    protected JWT jwt;

    public AbstractJWTPrincipal() {
    }

    public AbstractJWTPrincipal(JWT jwt) {
        this.jwt = jwt;
    }

    @Override
    public void eraseCredentials() {
        Optional.ofNullable(jwt).ifPresent(JWT::eraseCredentials);
    }

    public JWT getJwt() {
        return jwt;
    }

    @Override
    public String getName() {
        return Optional.ofNullable(jwt).map(JWT::getPayload).map(JWTPayload::getUsername).orElse("");
    }

    public void setJwt(JWT jwt) {
        this.jwt = jwt;
    }

    @Override
    public String toString() {
        return Optional.ofNullable(jwt).map(JWT::getTokenStr).orElse("");
    }
}
